package state

func (this *luaState) NewTable() {
	this.CreateTable(0, 0)
}

func (this *luaState) CreateTable(nArr, nRec int) {
	this.stack.push(NewLuaTable(nArr, nRec))
}

func (this *luaState) GetTable(idx int) LuaType {
	t := this.stack.get(idx)
	return this.getTable(t, this.stack.pop())
}
func (this *luaState) GetField(idx int, k string) LuaType {
	t := this.stack.get(idx)
	return this.getTable(t, k)
}
func (this *luaState) GetI(idx int, i int) LuaType {
	t := this.stack.get(idx)
	return this.getTable(t, i)
}
func (this *luaState) SetTable(idx int) {
	v := this.stack.pop()
	k := this.stack.pop()
	t := this.stack.get(idx)
	this._setTable(t, k, v)
}
func (this *luaState) SetField(idx int, k string) {
	v := this.stack.pop()
	t := this.stack.get(idx)
	this._setTable(t, k, v)
}
func (this *luaState) SetI(idx int, n int64) {
	v := this.stack.pop()
	t := this.stack.get(idx)
	this._setTable(t, n, v)
}

func (this *luaState) _setTable(t, k, v luaValue) {
	if tb, ok := t.(*LuaTable); ok {
		tb.Put(k, v)
	} else {
		panic("_setTable() t is not table")
	}
}

func (this *luaState) getTable(t, k luaValue) LuaType {
	tb, ok := t.(*LuaTable)
	if !ok {
		panic("GetTable not a table")
	}
	v := tb.Get(k)
	this.stack.push(v)
	return TypeOf(v)
}
